package com.aica.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;

/**
 * 文件的上传工具类
 * @author by
 * @date 2021/7/31 22:22
 */
@Component
@Slf4j
public class FileUtil {
    private String baseUrl;

    private String folder;

    private String[] imgType = new String[]{"image/jpg", "image/jpeg", "image/png", "image/gif", "image/bmp"};

    @Value("${my.upload-file.base-url}")
    public  void setBaseUrl(String baseUrl) {
        this.baseUrl = baseUrl;
    }

    public String getBaseUrl() {
        return baseUrl;
    }

    @Value("${my.upload-file.folder}")
    public  void setFolder(String folder) {
        this.folder = folder;
    }

    public String getFolder() {
        return folder;
    }


    public Boolean upLoadOneFile(MultipartFile file,String username,String path){
        //文件判空
        if(file==null || file.isEmpty()){
            return false;
        }


        //获得文件上传时的名字
        //String fileName = file.getOriginalFilename();
        //文件大小
        int size = (int) file.getSize();
        log.info(username + "当前上传文件：" + file.getOriginalFilename() + "，大小为-->" +size);
        //System.out.println(username + "上传的文件" + size);

        //根路径
        //String path = "G:/test" ;

        File dest = new File(baseUrl + folder + "/" + username + "/" +path);
        //判断文件父目录是否存在
        if(!dest.getParentFile().exists()){
            //不存在则创建文件目录
            boolean mkdir = dest.getParentFile().mkdir();
        }

        try {
            //保存文件
            file.transferTo(dest);
            return true;
        } catch (Exception e) {
            // TODO Auto-generated catch block
            log.info(username + "当前上传文件：" + file.getOriginalFilename() + "保存失败");
            //e.printStackTrace();
            return false;
        }
    }

    public Boolean upLoadPhoto(MultipartFile file,String username,String path){
        //文件判空
        if(file==null ||file.isEmpty()){
            return false;
        }
        String contentType = file.getContentType();
        if(StringUtils.isEmpty(contentType)){
            return false;
        }
        for (String s : imgType) {
            if(0==s.compareToIgnoreCase(contentType)){
                return upLoadOneFile(file,username,path);
            }
        }
        return false;
    }

}
